#include "clientdatabasemanager.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QJsonDocument>


ClientDatabaseManager& ClientDatabaseManager::instance()
{
    static ClientDatabaseManager singleton;
    return singleton;
}

ClientDatabaseManager::ClientDatabaseManager(QObject *parent) : QObject(parent)
{
    initDatabase();
}

ClientDatabaseManager::~ClientDatabaseManager()
{
    if (m_db.isOpen())
    {
        m_db.close();
        qDebug() << "ClientDatabaseManager::析构函数m_db关闭";
    }
}

void ClientDatabaseManager::initDatabase()
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
    // 将数据库文件命名为 qtalk_client.db 以区分
    m_db.setDatabaseName("qtalk_client.db");

    if (!m_db.open()) {
        qWarning() << "Client DB Error: Failed to open database:" << m_db.lastError().text();
        return;
    }
    qDebug() << "Client DB connected successfully.";

    QSqlQuery query;
    QString createTableSql = R"(
        CREATE TABLE IF NOT EXISTS Messages (
            message_id INTEGER PRIMARY KEY AUTOINCREMENT,
            from_id INTEGER NOT NULL,
            to_id INTEGER NOT NULL,
            content TEXT NOT NULL,
            timestamp INTEGER NOT NULL
        );
    )";
    if (!query.exec(createTableSql)) {
        qWarning() << "Client DB Error: Failed to create Messages table:" << query.lastError().text();
    } else {
        qDebug() << "Client Messages table is ready.";
    }
}

// --- 核心业务逻辑 ---

void ClientDatabaseManager::saveMessage(const QJsonObject &message)
{
    QSqlQuery query;
    query.prepare("INSERT INTO Messages (from_id, to_id, content, timestamp) "
                  "VALUES (:from_id, :to_id, :content, :timestamp)");

    query.bindValue(":from_id", message["from_id"].toInt());
    query.bindValue(":to_id", message["to_id"].toInt());
    query.bindValue(":content", message["content"].toString());
    qint64 timestamp = message["timestamp"].toInteger();
    query.bindValue(":timestamp",timestamp); // timestamp可能是大整数

    if (!query.exec()) {
        qWarning() << "Failed to save message to DB:" << query.lastError().text();
    }
}

QList<QJsonObject> ClientDatabaseManager::loadChatHistory(int userId1, int userId2)
{
    QList<QJsonObject> history;
    QSqlQuery query;
    // 查询所有与这两个用户相关的消息，并按时间戳升序排序
    query.prepare(R"(
        SELECT from_id, to_id, content, timestamp FROM Messages
        WHERE (from_id = :id1 AND to_id = :id2) OR (from_id = :id2 AND to_id = :id1)
        ORDER BY timestamp ASC
    )");
    query.bindValue(":id1", userId1);
    query.bindValue(":id2", userId2);

    if (!query.exec()) {
        qWarning() << "Failed to load chat history from DB:" << query.lastError().text();
        return history;
    }

    while(query.next()) {
        QJsonObject message;
        message["type"] = "private_message"; // 手动添加 type，方便复用
        message["from_id"] = query.value("from_id").toInt();
        message["to_id"] = query.value("to_id").toInt();
        message["content"] = query.value("content").toString();
        message["timestamp"] = query.value("timestamp").toLongLong();
        history.append(message);
    }
    return history;
}
